<template>
	<!-- 输入框组件
			接收search盒子，按钮，输入框，hover样式，
			提示文本placeholder，名字name获取浮窗设置
			获得焦点会显示历史记录，搜索会触发事件search，鼠标点击不在自己区域隐藏历史记录 -->
	<form class="search" :style="styles.box" @submit.prevent="handlerSearch">
		<div class="search-box">
			<input 
				name="search" 
				v-model="value" 
				:placeholder="placeholder" 
				:style="styles.search"
				@focus="focus=true" 
				@blur.self="lose" 
				autocomplete="off"
				/>
			<div 
				class="search-btn" 
				@click="handlerSearch" 
				:style="[styles.btn.styles, flag?styles.btn.inner:{}]" 
				@mouseenter="flag=true" 
				@mouseleave="flag=false"
				>
				<Icon type="search"/>
			</div>
		</div>
		<!-- 历史记录 -->
		<History v-if="focus" :sName="sName" @clear="clear" @handlerText="handlerText"/>
	</form>
</template>

<script>
import History from './History'
export default{
	data(){
		return{
			value: "",
			// 控制btn样式，等下弄掉不需要
			flag: false,
			// 获取到焦点
			focus: false,
			timer: undefined
		}
	},
	props:{
		// search的名字，用于保存查找该输入框的历史记录
		sName:{
			type: String,
			default: ''
		},
		// 输入框样式
		styles: {
			type: Object,
			default: () => ({
				btn: {}
			})
		},
		// 输入框提示
		placeholder:{
			type: String,
			default: '请输入'
		}
	},
	methods:{
		// 失去焦点，过一会隐藏历史记录，点击到历史记录面板就不隐藏，点击历史记录隐藏
		lose(){
			this.timer = setTimeout(()=>{
				this.focus = false;
			},200)
		},
		// 根据输入内容搜索，目前只保存消息记录
		handlerSearch(){
			clearTimeout(this.timer)
			this.$emit('search', this.value);
		},
		// 点击到历史记录上，清除要隐藏历史的定时器
		clear(){
			clearTimeout(this.timer)
		},
		// 点击历史搜索项，切换搜索词
		handlerText(val){
			this.value = val;
			this.lose();
		}
	},
	components:{
		History
	}
}
</script>

<style lang="less" scoped>
.search{
	width: 100%;
	height: 100%;
	position: relative;
	.search-box{
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		height: 100%;
		position: relative;
		border: 1px solid #e7e7e7;
		border-radius: 2px;
		box-sizing: border-box;
		input{
			width: 100%;
			height: 18px;
			margin: 0;
			padding: 0;
			padding-top: 1px;
			padding-right: 48px;
			text-indent: 15px;
			box-sizing: border-box;
			outline: none;
			border: 0;
			font-size: 14px;
			background-color: rgba(0,0,0,0);
			&::placeholder{
				color: var(--c9);
			}
		}
		.search-btn{
			position: absolute;
			right: 0;
			top: 50%;
			width: 40px;
			height: 100%;
			transform: translateY(-50%);
			cursor: pointer;
			color: #ccc;
			font-size: 19px;
		}
	}
}
</style>
